// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import {
    Button,
    Popup,
    Toast,
    Dialog,
    Actionsheet,
    DatetimePicker,
    NavBar,
    Uploader,
    NoticeBar,
    Row,
    Col,
    Picker,
    CellSwipe
} from 'vant';
import 'vant/lib/vant-css/base.css';
import ApiUrl from '../static/js/config'
import '../static/js/Controls'


Vue.config.productionTip = false;

Vue.component(Button.name, Button)
Vue.component(Col.name, Col)
Vue.component(Popup.name, Popup)
Vue.component(Toast.name, Toast)
Vue.component(Dialog.name, Dialog)
Vue.component(Actionsheet.name, Actionsheet)
Vue.component(DatetimePicker.name, DatetimePicker)
Vue.component(NavBar.name, NavBar)
Vue.component(Uploader.name, Uploader)
Vue.component(NoticeBar.name, NoticeBar)
Vue.component(Row.name, Row)
Vue.component(CellSwipe.name, CellSwipe)
Vue.component(Picker.name, Picker)
/* eslint-disable no-new */
let vue = new Vue({
    el: '#app',
    components: {App},
    template: '<App/>'
})
console.log(vue)
window.vm = vue.$children[0]

window.waitingDialog = {
    show: function (msg) {
        vm.$toast.loading(
            {
                mask: true,
                message: msg,
                duration: 0,
            }
        )
    },
    hide: function () {
        vm.$toast.clear()
    }
}
window.eModal = {
    iframe(data) {
        vm.frameOptions = data;
        vm.showIframe = true;
    },
    close() {
        vm.showIframe = false
    }
}
window.submitFormClickTime = null

window.toastr = {
    success(msg) {
        vm.$toast.success(msg)
    }
}
$(document).ready(function () {
    template.defaults.imports.dateFormat = function (date, format) {
        return date = moment.utc(date), date.format(format)
    }
    Dcqtech_Form.$form.on("Wf_Form.DataLoad", function () {
        console.info("Wf_Form.DataLoad Event");
    });

    Dcqtech_Form.$form.on("Wf_Form.DataBind", function () {
        console.info("Wf_Form.DataBind Event");
    });
    loadForm()
})


function filterButtons(toolButtons) {
    let actions = [];
    let bottomButtons = []
    if (toolButtons.indexOf("wf_form_submit()") != -1) {
        let item = {name: '提交', type: "info-success", callback: vm.actionSheetClick}
        actions.push(item)
    }
    if (toolButtons.indexOf("wf_form_save()") != -1) {
        let item = {name: '保存', type: "default", callback: wf_form_save}
        bottomButtons.push(item)
    }
    if (toolButtons.indexOf("wf_form_submit()") != -1) {
        let item = {name: '提交', type: "primary", callback: wf_form_submit}
        bottomButtons.push(item)
    }

    if (toolButtons.indexOf("wf_form_viewworkflow()") != -1) {
        let item = {name: '查看流程图', className: "info-text", callback: vm.actionSheetClick}
        actions.push(item)
    }
    if (toolButtons.indexOf("wf_form_stop()") != -1) {
        let item = {name: '终止', type: "red-text", callback: vm.actionSheetClick}
        actions.push(item)
    }

    if (toolButtons.indexOf("wf_form_remove()") != -1) {
        let item = {name: '删除', className: "red-text", callback: vm.actionSheetClick}
        actions.push(item)
    }

    vm.actions = actions
    vm.bottomButtons = bottomButtons

}

/**
 * 设置datepicker 选择器
 * @param format 格式化字符串
 * @param selector 选择标识
 * @param date_string 日期字符串
 */
window.setupDatePicker = function (format, selector, date_string) {
    vm.showDatePicker = true
    vm.dateFormat = format == "yyyy-mm-dd" ? "date" : "datetime"
    let date = moment(date_string)
    if (date_string) {
        vm.currentDate = date._d
        console.log(date._d)
    } else {
        vm.currentDate = new Date()
    }

    vm.target = selector
}

/**
 * 加载form表单
 */
function loadForm() {

    $(".loading-container").show()
    window.token = ""
    if (process.env.NODE_ENV === 'development') {
        // dev
        token = "&Dcqtech_Token=039eb7d581034b4499e7973982609c1f"
    } else {
        // build
    }
    $.get(ApiUrl.prefix + "/WorkFlowRuntime/Form/GetFormIdsByWf" + location.search +
        token, function (res) {

        if (res.Data) {
            let forms = res.Data.forms
            let stepInfos = res.Data.stepInfos
            let stepId = stepInfos.stepId
            window.g_stepid = stepId
            window.g_workInfo = res.Data.workInfo
            window.g_stepInfos = stepInfos
            window.g_editFormCount = 0
            let datas = res.Data.forms;
            for (let i = 0; i < datas.length; i++) {
                let data = datas[i];
                // let icon = data.type == "edit" ? '<i class="menu-icon fa fa-edit"></i> ' : '';
                // let title = data.type == "edit" ? '编辑表单：' : '查看表单：';
                // title = "title='" + title + data.name + "'";
                if (data.type == "edit") window.g_editFormCount++;
                // html.push('<li formid="', data.id, '" ', title, ' type="', data.type, '" ><a href="javascript:void(0)" onclick="return false;">', icon, data.name, '</a></li>');
            }
            filterButtons(res.Data.stepInfos.toolButtons)
            vm.form = forms[0]
            let formUrl = ""
            if (vm.form.type == "edit") {
                formUrl = "/WorkFlowRuntime/Form/GetFormInfoByWfId"
            } else {
                formUrl = "/WorkFlowRuntime/Form/GetFormViewInfo"
            }

            let search = location.search + "&formid=" + forms[0].id + "&stepid=" + stepId + token
            window.search = search
            $.get(ApiUrl.prefix + formUrl + search,
                function (res) {
                    // console.log(res)
                    let ret = res.Data
                    Dcqtech_Form.formInfos = res.Data;
                    let formInfos = res.Data.formInfos;
                    insertHtml(formInfos.htmls);
                    insertJS(res.Data.customJs);
                    insertCSS(res.Data.customCss);
                    Dcqtech_Form.formInfos.stepInfos = stepInfos;
                    document.title = res.Data.formName;

                    Dcqtech_Form.tableInfos = {};
                    if (!ret.tableInfo) {
                        alert("没有tableInfo，可能是老表单，请重新编辑！ ");
                    }
                    for (let i = 0; i < ret.tableInfo.length; i++) {
                        Dcqtech_Form.tableInfos[ret.tableInfo[i].id] = ret.tableInfo[i];
                    }


                    vm.formInfos = formInfos;
                    loadData(search);
                })
        } else {
            $("#loading").hide()
            $(".loading-container .oa-lock").show()
            $("#loading-text").text(res.Message)
        }

    })


}

function insertCSS(css) {
    if (css) {
        $(document.body).append('<style id="customCss">' + css + '</style>');
    }
}

/**
 * 加载数据
 * @param search search的字符串
 */
function loadData(search) {
    vm.search = search
    let dataUrl = ""
    if (vm.form.type == "edit") {
        dataUrl = "/WorkFlowRuntime/Form/Load"
    } else {
        dataUrl = "/WorkFlowRuntime/Form/LoadView"
    }
    $.getJSON(ApiUrl.prefix + dataUrl + search, {_t: +new Date}, function (res) {

        if (res.Data) {
            let json = JSON.parse(res.Data.JSON)
            console.log(json)
            let id = json.data.id
            let formData = json.data.datas[id].Datas[0]
            vm.formData = formData
            Dcqtech_Form.lastDatas = json.data
            Dcqtech_Form.formSaveGuid = res.Data.DATAGUID

        }
        if (res.Data) {
            showOpinions(res.Data.OPINIONS);
        }
        else {
            showOpinions(null);
        }
        setupData()

    });
}

window.dateFormat = function (data, format) {

    data = moment.utc(data);
    return data.format(format);

}

function insertHtml(html) {
    console.log()
    let reg = /style\s*?=\s*?([‘"])[\s\S]*?\1/;
    // html = html.replace(new RegExp(reg, 'g'), "")
    html = html.replace(new RegExp('&nbsp;', 'g'), "")
    html = html.replace(" 添加附件 ", "")

    // let p = $(html).find("p")
    $("#udf_wf_form").html(html)

    // alert("加载完成")

    // $('.form-group .input-group .list-group').append("<a target=\"_blank\" href=\"/WorkFlowRuntime/Attachment/download?id=cdca569a437c4598ad18d3c65fce40da.png\"><span role=\"filename\">icon-57@2x.png</span></a>")

}

window.isInteger = function (obj) {
    return Math.floor(obj) === obj
}

function setupMobileUI() {
    $(".form-group").css("height", "auto")
    $(".form-group .fileinput-button>i").remove()
    // $(".form-group .input-group").css("width", "auto")
    let file_cell = $('.form-group .input-group')
    let textareaCell = $(".form-group textarea")
    // file_cell.parent().css("display", "block")
    // file_cell.parent().css("width", "calc(100% - 30px)")
    textareaCell.parent().css("width", "100%");
    textareaCell.parent().css("padding", "0");
    // console.log()

    $(".form-group input:required").parent().prev(".control-label").addClass("required")
    $(".form-group textarea:required").parent().prev(".control-label").addClass("required")
    // file_cell.css("height",'44px')
    // file_cell.addClass("file-cell");
    // file_cell.find(".form-control").hide()
    // file_cell.parent().next(".control-label").addClass("file-cell-control")
    // file_cell.find(".input-group-btn").hide()
    // file_cell.append("<span class='files-tips'>0个附件</span><i class='iconfont oa-jiantou'></i>")
    //
    // vm.filesTargets = []
    // file_cell.each((index, element) => {
    //     let id = $(element).attr("dcqtech_id")
    //     console.log($(element))
    //     let fileTarget = {id: id, filesList: [], showFilesManager: false}
    //     vm.filesTargets.push(fileTarget)
    //     // // loadFiles(index)
    //     let ids = $(element).children("[dcqtech_data=" + id + "]").val()
    //     loadFiles(index, id, ids)
    // })
    // file_cell.on("click", function () {
    //     let index = $(this).index()
    //     console.log((index))
    //     vm.filesTargets[index].showFilesManager = true
    // })
}

window.loadFiles = function (id, ids) {
    if (ids) {
        $.getJSON(ApiUrl.prefix + "/WorkFlowRuntime/Attachment/GetByIds?ids=" + ids + token, function (ret) {
            if (ret.Error == 0) {
                vm.filesTargets.forEach((item) => {
                    if (item.id == id) {
                        item.filesList = ret.Data
                        $("[dcqtech_id=" + id + "] .files-tips").text(item.filesList.length + "个附件")
                    }
                })
            }
        });
    } else {

    }
}

window.upload = function (file) {
    let fd = new FormData();
    fd.append("files[]", file);//上传的文件： 键名，键值
    let token = ""
    if (process.env.NODE_ENV === 'development') {
        // dev
        token = "?Dcqtech_Token=00da555895394ba6b9d4aaae3c9d5620"
    } else {
        // build
    }
    $.ajax({
        url: ApiUrl.prefix + "/WorkFlowRuntime/Attachment/upload" + token,
        type: 'POST',
        cache: false,
        data: fd,
        processData: false,
        contentType: false,
        dataType: "json",
        beforeSend: function () {
            vm.$toast.loading({
                mask: true,
                message: "上传文件中"
            })
        },
        success: function (data) {
            console.log(data)
            if (data.Data.success) {
                let fileItem = data.Data.success[0]
                console.log(fileItem)
                for (let i = 0; i < vm.filesTargets.length; i++) {
                    let item = vm.filesTargets[i]
                    if (item.showFilesManager == true) {
                        item.filesList.push(fileItem)
                        let values = item.filesList.map((item) => {
                            return item.GUID
                        }).join(",")
                        $("[dcqtech_data=" + item.id + "]").val(values)
                        $("[dcqtech_id=" + item.id + "] .files-tips").text("共" + item.filesList.length + "个附件")
                    }
                }
            }
            // uploading = false;
            vm.$toast.clear()
        }
    });

};

/**
 * 设置数据
 */
function setupData() {
    let formInfos = vm.formInfos
    if (formInfos) {

        for (let key in formInfos.fieldInfos) {
            // console.log(key)
            let item = formInfos.fieldInfos[key]
            let controls = Dcqtech_Form_Controls[item.dcqtechWidget];
            if (controls) {
                let fieldInfo = formInfos.fieldInfos[key];
                controls.setDefaultValue(fieldInfo.id, Dcqtech_Form.$form, fieldInfo);
                controls.setEditEvent(fieldInfo.id, fieldInfo, Dcqtech_Form.$form);
                controls.setReadonly(fieldInfo.id, fieldInfo.isReadOnly, fieldInfo, Dcqtech_Form.$form);
            }

        }
    }
    if (vm.formData) {
        Dcqtech_Form.bindDataItem(vm.formInfos, vm.formData)
    }
    setupMobileUI();
    Dcqtech_Form.$form.trigger("Wf_Form.DataBind");
    $(".loading-container").hide()

}

Dcqtech_Form.bindDataItem = function (formInfos, dts) {
    console.info(formInfos, dts);
    let fieldInfos = formInfos.fieldInfos;

    for (let fid in fieldInfos) {
        // try {
        let fieldInfo = fieldInfos[fid];
        // if (fieldInfo.notSave) continue;

        let controls = Dcqtech_Form_Controls[fieldInfo.dcqtechWidget];
        let value = dts[fieldInfo.field]
        console.log(value)
        controls.setValue(fid, value, fieldInfo, Dcqtech_Form.$form, true);
        controls.setEditEvent(fid, fieldInfo, Dcqtech_Form.$form);
        // } catch (e) {
        //     console.warn(e, fid);
        // }

    }
    //bind

    if (formInfos.children && formInfos.children.length) {
        for (let i = 0; i < formInfos.children.length; i++) {
            Dcqtech_Form.bindDataItem(formInfos.children[i], dts.children[formInfos.children[i].id]);
        }
    }

}

/**
 * 搜索
 * @param name
 * @returns {null}
 * @constructor
 */
function GetQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/**
 * 插入js
 * @param js js字符串
 */
function insertJS(js) {
    if (js) {
        $(document.body).append('<script>' + js + '<\/script>');
    }
    Dcqtech_Form.$form.trigger("Wf_Form.DataLoad");
    let iframes = $(".form-group div.col-xs-12>iframe")
    vm.customFrames = []
    $("#iframediv").remove()
    iframes.each(function (index, element) {
        let src = $(element).attr("src");
        $(element).attr("data-src", src)
        $(element).attr("src", "")
        let title = $(element).parent().prev().text()
        let item = {id: src + index, url: ApiUrl.host + src, title: title, showPopup: false}
        vm.customFrames.push(item)
    })
    iframes.hide()

    iframes.parent().addClass("iframe-cell")
    iframes.parent().append("<span class='tips'>点击查看</span><i class='iconfont oa-jiantou'></i>")
    iframes.parent().on("click", function () {
        let index = $(this).children("iframe").index();
        vm.customFrames[index].showPopup = true
        console.log(index)
    })
}

window.wf_form_viewworkflow = function () {
    eModal.iframe({
        "url": Dcqtech.Url.Content("/WorkFlow/UDF_WorkFlowView/Index" + location.search),
        "height": "600px",
        "title": "查看流程图"
    });
}

window.wf_form_save = function (fn) {
    vm.showAction = false
    if (window.Dcqtech_form_beforsave) {
        let t = window.Dcqtech_form_beforsave();
        if (!t) {
            console.info("Dcqtech_form_beforsave 未返回true，退出返回");
            return
        }
    }
    if ($.html5Validate.isAllpass($("#udf_wf_form"))) {
        console.info("验证通过");
        if (fn instanceof Function) {
            doSave(1, fn)
        } else {
            doSave(1, null);
        }
    }

}

window.submitNext = function () {
    console.info(parent.nextStepInfo);
    let nextStepInfo = parent.nextStepInfo;
    if (nextStepInfo && nextStepInfo.canClose) {
        let stepId = nextStepInfo.stepId;
        let userIds = nextStepInfo.userIds;
        parent.eModal.close();
        parent.waitingDialog.show("提交中。。。");
        $.getJSON("gotoNextStep" + location.search, {
            nextstepid: stepId,
            nextuserids: userIds.join(",")
        }, function (ret) {
            parent.waitingDialog.hide();
            alert("提交成功！");
            parent.location.href = Dcqtech.Url.Content("~/WorkFlowPortal/WFE_TodoTask/List");
            //location.href = "?wfid=" + Dcqtech.Url.getParam("wfid") + "&formid=" + Dcqtech.Url.getParam("formid") + "&stepid=" + stepId;
        });

    } else {
        alert("请选择下一阶段人员！");
    }
}

window.wf_form_submit = function () {
    if ($.html5Validate.isAllpass($("#udf_wf_form"))) {
        console.info("验证通过");
        doSave(1, function () {
            console.info("保存成功！");

            // vm.frameTitle = "选择下一阶段";
            // vm.frameUrl = "http://192.168.11.30:88"+"/WorkFlowRuntime/Form/selectNextStep"+location.search

            parent.eModal.iframe({
                "url": "/WorkFlowRuntime/Form/selectNextStep" + vm.search,
                "title": "选择下一阶段",
                "buttons": [{
                    text: '取消',
                    style: 'danger',
                    close: true
                }, {
                    text: '选择',
                    style: 'info',
                    close: false,
                    click: function () {
                        console.info(parent.nextStepInfo);

                        let now = new Date().getTime();
                        if (submitFormClickTime) {
                            if (now - submitFormClickTime < 1000) {
                                console.info("两次提交时间间隔太短");
                                return;
                            }
                        }

                        submitFormClickTime = now;
                        let iframe = $('.modal-content iframe')[0];
                        console.log(iframe);
                        let nextsteps = iframe.contentWindow.checkSelectUser();
                        if (!nextsteps.canClose) return;
                        let steps = {};
                        for (let i = 0; i < nextsteps.users.length; i++) {
                            steps[nextsteps.users[i].stepId] = nextsteps.users[i].users.join(",");
                        }

                        eModal.close();
                        waitingDialog.show("提交中");
                        $.post("/WorkFlowRuntime/Form/gotoNextStep" + vm.search, {
                            nextStepListText: JSON.stringify(steps),
                            gateWayId: nextsteps.gateWayId
                        }, function (ret) {
                            console.info(ret);
                            alert("提交成功！");
                            location.href = Dcqtech.Url.Content("~/WorkFlowPortal/WFE_TodoTask/List");
                        });

                        //     let nextStepInfo = parent.nextStepInfo;
                        // if (nextStepInfo && nextStepInfo.canClose) {
                        //     let stepId = nextStepInfo.stepId;
                        //     let userIds = nextStepInfo.userIds;
                        //     parent.eModal.close();
                        //     parent.waitingDialog.show("提交中。。。");
                        //     $.getJSON("/WorkFlowRuntime/Form/gotoNextStep" + vm.search, {
                        //         nextstepid: stepId,
                        //         nextuserids: userIds.join(",")
                        //     }, function (ret) {
                        //         parent.waitingDialog.hide();
                        //         alert("提交成功！");
                        //         parent.location.href = Dcqtech.Url.Content("~/WorkFlowPortal/WFE_TodoTask/List");
                        //         //location.href = "?wfid=" + Dcqtech.Url.getParam("wfid") + "&formid=" + Dcqtech.Url.getParam("formid") + "&stepid=" + stepId;
                        //     });
                        //
                        // } else {
                        //     alert("请选择下一阶段人员！");
                        // }
                    }
                }]
            });

        });
    }
}

function doSave(type, fn) {
    //type == 0 :save  type==1:提交
    type = (type == 1) ? 1 : 0;
    parent.waitingDialog.show("数据保存中");
    let formData = getSaveData(Dcqtech_Form.formInfos.formInfos, Dcqtech.Url.getParam("wfid"));
    console.info(formData, Dcqtech_Form.lastDatas);
    let saveData = {
        json: JSON.stringify({
            data: formData
        }),
        DATAGUID: Dcqtech_Form.formSaveGuid,
        opinionsCount: (Dcqtech_Form.formInfos.stepInfos.hasOpinion == 0 ? 0 : Dcqtech_Form.formInfos.stepInfos.personCount)
    };
    //意见栏
    let opinions = null;
    if (Dcqtech_Form.formInfos.stepInfos.hasOpinion) {
        opinions = {};
        $(".dcq_Opinion_main [pName]").each(function () {
            opinions[$(this).attr("pName")] = this.value;
            //opinions = data;
        });
        //opinions.CREATETIME = parseInt(opinions.CREATETIME, 10);
        saveData.opinions = JSON.stringify(opinions);
    }


    //提交保存数据到后台数据库。
    $.post(ApiUrl.prefix + "/WorkFlowRuntime/Form/Save/" + type + vm.search, saveData, function (ret) {
        parent.waitingDialog.hide();
        console.info(ret);
        if (ret.Error) {
            if (ret.Error == 100) {
                let msg = JSON.parse(ret.Message);
                parent.eModal.alert("当前页面已经在<b>" + msg.SAVETIME + "</b>被<b>" + msg.USERNAME + "</b>编辑过！<br />请刷新页面加载最新的数据！", "编辑冲突!");
                return;
            }
            else {
                alert(ret.Message);
                return;
            }

        } else {
            Dcqtech_Form.formSaveGuid = ret.Data;
            parent.toastr.success("保存成功");
            Dcqtech_Form.saved = true;
        }
        if (fn) {
            fn();
        }
    });

    //console.info(saveData);
}

/*
 * 数据保存相关逻辑
 */


function getSaveData(formInfos, guid) {
    let savedatas = {
        id: formInfos.id,
        dataCount: 0
    };
    let wfid = GetQueryString("wfid");
    let datas = {};
    let tables = [];
    for (let id in formInfos.fieldInfos) {
        //for (let indexField = formInfos.fieldInfos.length - 1; indexField >= 0; indexField--) {
        let fieldInfo = formInfos.fieldInfos[id];
        //let id = fieldInfo.id;

        if (fieldInfo.notSave) continue;
        if (fieldInfo.dcqtechWidget == "RepeatTable") continue;  //TODO: delete

        if (!fieldInfo['tableInfoID']) {
            console.warn("未绑定数据：", fieldInfo);
            continue;
        }
        let tableKey = fieldInfo['tableInfoID'];
        let data = datas[tableKey];
        let $control = $("[dcqtech_data='" + id + "']");
        if (!data) {
            data = {
                tableInfoID: fieldInfo['tableInfoID'],
                Datas: [],
                FieldType: {},
                Length: $control.length
            };
            let tbInfo = Dcqtech_Form.tableInfos[tableKey];
            tables.push(tableKey);
            for (let i = 0; i < $control.length; i++) {
                let o = {};
                o[tbInfo.keyfield] = wfid + "_" + i;
                data.Datas.push(o);
            }
            datas[tableKey] = data;

            savedatas.dataCount += $control.length;
        }
        let field = fieldInfo.field;
        if (!field) {
            console.warn("field为空！", fieldInfo);
            continue;
        }
        let fieldType = fieldInfo.fieldType;
        let getFn = getData_default;
        switch (fieldType) {
            case "string":
                break;
            case "DateTime":
                data.FieldType[field] = fieldType;
                break
            case "long":
            case "smallint":
            case "int":
            case "byte":
                getFn = getData_int;
                break;
            case "double":
            case "float":
            case "decimal":
                getFn = getData_float;
                break;
            case "Guid":
                break;
            case "bool":
                break;
            default:
                // statements_def
                break;
        }
        $("[dcqtech_data='" + id + "']").each(function (index) {
            Dcqtech_Form_Controls[fieldInfo.dcqtechWidget].beforeSave(id, this);
            data.Datas[index][field] = getFn(this.value);
            //data.Datas[index]["DCQ_WF_GID"] = guid + "_" + index;
        });
    }
    savedatas.datas = datas;
    savedatas.tables = tables;
    if (tables.length > 1) {
        console.warn("多表单绑定！！", tables);
    }
    if (formInfos.children && formInfos.children.length) {
        savedatas.children = {};
        for (let i = 0; i < formInfos.children.length; i++) {
            savedatas.children[formInfos.children[i].id] = (getSaveData(formInfos.children[i], guid + "_" + i));
        }
    }
    if (formInfos.id == "main") {
        let mainKey = Dcqtech_Form.tableInfos["main"].keyfield;
        savedatas.datas.main.Datas[0][mainKey] = guid;
    }
    return savedatas;
}

function getData_default(value) {
    return value;
}

function getData_int(value) {
    if (value) return parseInt(value, 10);
    else return null;
}

function getData_float(value) {
    if (value) return parseFloat(value);
    else return null;
}


window.wf_form_stop = function () {
    if (!confirm("确定要终止任务吗？")) return;

    wf_form_save(function () {
        $.getJSON("TerminateProcess" + location.search, {"_t": +new Date()}, function (ret) {
            if (ret.Error) {
                alert(ret.Message);
            } else {
                location.href = Dcqtech.Url.Content("~/WorkFlowPortal/WFE_TodoTask/List");
            }
        });
    });
}

/**
 * 显示意见栏
 */
window.showOpinions = function (opinions) {
    if (!opinions) opinions = [];
    //if(Dcqtech_Form.formInfos.stepInfos.hasOpinion)
    let html = ["<div class='dcq_Opinion_main'>"];
    let lastStepGuid = null;
    let opinionTemplete = "<div class='dcq_Opinion'><div class='opinionContent'>{{ CONTENTS }}</div><div><span class='opinionName'>{{ USERNAME }}</span><span class='pull-right'>{{ CREATETIME | dateFormat:'YYYY年MM月DD日 HH时mm分' }}</span>  </div> </div>";
    let templete = template.compile(opinionTemplete);
    console.log(templete)
    let editOpinions = [];
    while (true) {
        let opinion = opinions.shift();
        if (!opinion) break;
        if (opinion.TYPE == "CURRENT") {
            editOpinions.push(opinion);
            continue;
        }
        let groupStepGuid = opinion.STEP_ID;
        if (lastStepGuid != groupStepGuid) {
            if (lastStepGuid != null) {
                html.push("</fieldset>");
            }
            lastStepGuid = groupStepGuid;
            html.push("<fieldset><legend>" + opinion.STEP_NAME + "</legend>");
        }

        html.push(templete(opinion));
    }
    if (html.length > 0) {
        html.push("</fieldset>");
    }

    if (Dcqtech_Form.formInfos.stepInfos.hasOpinion > 0) {
        if (Dcqtech_Form.formInfos.stepInfos.personCount == 1) {
            let editOpin = null;
            if (editOpinions.length > 0) {
                editOpin = editOpinions[0];
            }
            else {
                editOpin = {
                    "CONTENTS": "",
                    "USERID": ServerParam.UserId,
                    "USERNAME": ServerParam.UserName,
                    "CREATETIME": dateFormat(ServerParam.CurrentTime, "YYYY-MM-DD HH:mm:ss"),
                    "STEP_NAME": Dcqtech_Form.formInfos.stepInfos.stepName,
                    "STEP_ID": Dcqtech_Form.formInfos.stepInfos.stepGuid
                };
            }
            let editopinionTemplete = "<fieldset><legend>{{ STEP_NAME }}</legend><div><textarea pName='CONTENTS'  class='opinionEdit  autoheight' required>{{ CONTENTS }}</textarea></div>" +
                "<div><span>{{ USERNAME }}</span><span class='replayButton'>常用意见</span><span class='pull-right'>{{ CREATETIME | dateFormat:'YYYY年MM月DD日 HH时mm分' }}</span></div>" +

                "<input type='hidden' pName='STEP_ID' value='{{STEP_ID}}' />" +
                "<input type='hidden' pName='STEP_NAME' value='{{STEP_NAME}}' />" +
                "<input type='hidden' pName='USERNAME' value='{{USERNAME}}' />" +
                "<input type='hidden' pName='USERID' value='{{USERID}}' />" +
                "<input type='hidden' pName='CREATETIME' value='{{CREATETIME}}' /> </fieldset>";
            html.push(template.render(editopinionTemplete,editOpin));
        }
        else {
            console.info(editOpinions);
            html.push("<fieldset><legend>" + Dcqtech_Form.formInfos.stepInfos.stepName + "</legend>");
            let editOpin = null;
            for (let i = 0; i < editOpinions.length; i++) {
                if (editOpinions[i].USERID == ServerParam.UserId) {
                    editOpin = editOpinions[i];
                }
                else {
                    html.push(templete(editOpinions[i]));  //显示同一节点其它人意见？？
                }
            }
            if (editOpin == null) {
                editOpin = {
                    "CONTENTS": "",
                    "USERID": ServerParam.UserId,
                    "USERNAME": ServerParam.UserName,
                    "CREATETIME": dateFormat(ServerParam.CurrentTime, "YYYY-MM-DD HH:mm:ss"),
                    "STEP_NAME": Dcqtech_Form.formInfos.stepInfos.stepName,
                    "STEP_ID": Dcqtech_Form.formInfos.stepInfos.stepGuid
                };
            }

            let editopinionTemplete = "<div><textarea pName='CONTENTS'  class='opinionEdit  autoheight' required>{{ CONTENTS }}</textarea></div>" +
                "<div><span>{{ USERNAME }}</span><span class='replayButton'>常用意见</span> <span class='pull-right'>{{ CREATETIME | dateFormat:'YYYY年MM月DD日 HH时mm分' }}</span></div>" +

                "<input type='hidden' pName='STEP_ID' value='{{STEP_ID}}' />" +
                "<input type='hidden' pName='STEP_NAME' value='{{STEP_NAME}}' />" +
                "<input type='hidden' pName='USERNAME' value='{{USERNAME}}' />" +
                "<input type='hidden' pName='USERID' value='{{USERID}}' />" +
                "<input type='hidden' pName='CREATETIME' value='{{CREATETIME}}' />";

            html.push(template.render(editopinionTemplete,editOpin));

            html.push("</fieldset>");


        }
    }
    //else if (Dcqtech_Form.formInfos.stepInfos.hasOpinion == 2) {
    //    console.warn("//TODO:多人查看");
    //}

    html.push("</div>");

    if (html.length > 3) {
        Dcqtech_Form.$form.append(html.join(""));
    }

    $(".replayButton").on("click",function () {
        vm.showOptions = true
    })

}

window.wf_form_remove = function () {
    if (!confirm("确定要删除任务吗？")) return;
    frames["frame_form"].Dcqtech_Form.lastClickButton = "remove";
    $.getJSON("RemoveInitProcess" + location.search, function (ret) {
        if (!ret.Data) {
            alert("只有未进入流程的任务才可以删除！");
        } else {
            location.href = Dcqtech.Url.Content("~/WorkFlowPortal/WFE_TodoTask/List");
        }
    });
}